package co.yixiang.modules.pay.weixin;


import co.yixiang.modules.pay.zhifubao.HttpRequestUtil;
import co.yixiang.modules.pay.zhifubao.MD5Util;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.util.*;

/**
 * #(c) IFlytek mangguo <br/>
 * <p>
 * 版本说明: $id:$ <br/>
 * <p>
 * 功能说明: 公共平台接口类，请求菜单
 * <p>
 * <p>
 * <br/>创建说明: 2014-3-24 下午03:41:40 L H T  创建文件<br/>
 * <p>
 * 修改历史:<br/>
 */
public class WeiXin {
    private static Logger log = LoggerFactory.getLogger(WeiXinUtil.class);

    //信息已是正式的
    private static String characterEncoding = "UTF-8";
    //↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓  智慧医疗微信参数 ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
    //APPID
    public static String WEIXIN_APP_ID = "wx87d5f65acb5ee510";
    //商户号
    public static String WEIXIN_MCH_ID = "1556993541";
    //支付秘钥
    public static String WEIXIN_PAY_KEY = "2u0mb2pxWfGGwo65PSaC3kQIe1hOJp3F";

    public static String WEIXIN_APP_Secret = "f4f301a43469f5b46ac16d7fc7817c3a";


    public static final String TRANSFERS_PAY = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"; // 企业付款API


    //↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ 智慧医疗微信参数 ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

    public static String XIAOCHENXU_PAY_KEY = "97f8035a04312442dd0a52bbe2d06b26";  //小程序秘钥


    public static String payToUser(WxPayToUserData data, String key){
        String returnXml = null;
        try {
            //生成sign签名
            SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
            parameters.put("mch_appid", data.getMch_appid());
            parameters.put("mchid", data.getMchid());
            parameters.put("nonce_str", data.getNonce_str());
            parameters.put("partner_trade_no", data.getPartner_trade_no());
            parameters.put("openid", data.getOpenid());
            parameters.put("check_name", data.getCheck_name());
            parameters.put("re_user_name", data.getRe_user_name());
            parameters.put("amount", data.getAmount());
            parameters.put("desc", data.getDesc());
            parameters.put("spbill_create_ip", data.getSpbill_create_ip());
            log.info("SIGN:"+WeiXinUtil.createSign(parameters,key));
            data.setSign(WeiXinUtil.createSign(parameters,key));

            XStream xs = new XStream(new DomDriver("UTF-8",new XmlFriendlyNameCoder("-_", "_")));
            xs.alias("xml", WxRefundData.class);
            String xml = xs.toXML(data);
            log.info("微信付款给用户xml为:\n" + xml);
            //returnXml = HttpRequestUtil.sendPostXml("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers", xml);
            returnXml = HttpRequestUtil.sendCertPostXml("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers",data.getMchid(), xml);
            log.info("返回结果:" + returnXml);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnXml;
    }

    /**
     * 功能描述:微信支付第一步——统一下单
     *
     * @param data
     * @param key
     * @return
     * @author yanzy  2016-1-18 下午10:01:20
     */
    public static String unifiedOrder(WxPaySendData data, String key) {
        System.out.println("=========================data:" + data);
        System.out.println("=========================key:" + key);
        //统一下单支付
        String returnXml = null;
        try {
            //生成sign签名
            SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
            parameters.put("appid", data.getAppid());
            parameters.put("attach", data.getAttach());
            parameters.put("body", data.getBody());
//          parameters.put("key", data.getKey());
            parameters.put("mch_id", data.getMch_id());
            parameters.put("nonce_str", data.getNonce_str());
            parameters.put("notify_url", data.getNotify_url());
            parameters.put("openid", data.getOpenid());
            parameters.put("out_trade_no", data.getOut_trade_no());
            parameters.put("spbill_create_ip", data.getSpbill_create_ip());
            parameters.put("total_fee", data.getTotal_fee());
            parameters.put("trade_type", data.getTrade_type());
//            parameters.put("device_info", data.getDevice_info());
            //  data.setSign(WeiXinUtil.createSign(characterEncoding,parameters));
            data.setSign(WeiXinUtil.createSign(parameters, key));

            XStream xs = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
            xs.alias("xml", WxPaySendData.class);
            String xml = xs.toXML(data);
            log.info("统一下单xml为:\n" + xml);
            returnXml = HttpRequestUtil.sendPostXml("https://api.mch.weixin.qq.com/pay/unifiedorder", xml);
            log.info("返回结果:" + returnXml);
            System.out.println("=============================返回结果:" + returnXml);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnXml;
    }


    /**
     * 微信支付签名算法sign
     *
     * @param characterEncoding
     * @param parameters
     * @return
     */
    @SuppressWarnings("unchecked")
    public static String createSign(String characterEncoding, SortedMap<Object, Object> parameters) {
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v)
                    && !"sign".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + WeiXinUtil.WEIXIN_MCH_ID);
        System.out.println("accsii排序:====" + sb.toString());
        String sign = MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }


    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname))
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            else
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetname)));
        } catch (Exception exception) {
        }
        return resultString;
    }

    private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    @SuppressWarnings("rawtypes")
    public static String createSign(SortedMap<Object, Object> parameters, String key) {
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v)
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + key);
        String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }

    /**
     * 功能描述:生成随机字符串
     *
     * @return
     * @author yanzy  2016-1-18 下午07:11:35
     */
    public static String getNonceStr() {
        Random random = new Random();
        return MD5Util.MD5Encode(String.valueOf(random.nextInt(10000)), "UTF-8");
    }

    /**
     * 功能描述:时间戳
     *
     * @return
     * @author yanzy  2016-1-18 下午07:11:53
     */
    public static String getTimeStamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }

    /**
     * 功能描述: 获取客户端IP
     *
     * @param request
     * @return
     * @author yanzy  2016-1-18 下午08:19:45
     */
    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 功能描述:微信退款
     *
     * @param data
     * @param key
     * @return
     * @author yanzy  2016-10-25 下午01:52:19
     */
    public static String refund(WxRefundData data, String key) {
        String returnXml = null;
        try {
            //生成sign签名
            SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
            parameters.put("appid", data.getAppid());
            parameters.put("mch_id", data.getMch_id());
            parameters.put("nonce_str", data.getNonce_str());
            parameters.put("out_trade_no", data.getOut_trade_no());
            parameters.put("out_refund_no", data.getOut_refund_no());
            parameters.put("total_fee", data.getTotal_fee());
            parameters.put("refund_fee", data.getRefund_fee());
            parameters.put("op_user_id", data.getOp_user_id());
            log.info("SIGN:" + WeiXinUtil.createSign(parameters, key));
            data.setSign(WeiXinUtil.createSign(parameters, key));
            XStream xs = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
            xs.alias("xml", WxRefundData.class);
            String xml = xs.toXML(data);
            log.info("微信退款xml为:\n" + xml);
            returnXml = HttpRequestUtil.sendCertPostXml("https://api.mch.weixin.qq.com/secapi/pay/refund", data.getMch_id(), xml);
            log.info("返回结果:" + returnXml);

            XStream xs1 = new XStream(new DomDriver());
            xs1.alias("xml", WxRefundData.class);
            WxRefundData reData = (WxRefundData) xs1.fromXML(returnXml);

            System.out.println("==========解析结果==============" + reData.getResult_code());
            return reData.getResult_code();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }



}
